<template>
    <div>
        <Teleport to="#after-navigation" v-if="targetExists">
            <ForumManager />
        </Teleport>
        <div class="title-wrap">
            <h2>{{ $t('messgae.title') }}</h2>
            <el-button color="#F16C2E" @click="showAddMessageDialog()">{{ $t('messgae.btnTxt') }}</el-button>
        </div>

        <div class="notices-wrap">
            <div class="notices-left">
                <ul v-if="dataList.length > 0" v-loading="listLoading">
                    <li v-for="(item, index) in dataList" :key="item.id" :class="item.id == activeItemId ? 'active' : ''" @click="clickDetailAction(item)">
                        <h3>{{ item.title }}</h3>
                        <div>
                            <p>{{ formatLoginTime(item.created_at) }}</p>
                        </div>
                    </li>
                    <div class="pagination-box">
                        <el-pagination
                            size="small"
                            background
                            v-model:page-size="pagination.limit"
                            v-model:current-page="pagination.page"
                            layout="prev, pager, next"
                            :total="pagination.total"
                            :page-sizes="[10, 20, 50, 100]"
                            :pager-count="6"
                            class="mt-4"
                            :hide-on-single-page="true"
                            @size-change="getDataList"
                            @current-change="getDataList"
                        />
                    </div>
                </ul>
                <p v-else class="no-data-list-tips">{{ $t('messgae.no_data_txt') }}</p>
            </div>
            <div class="notices-right">
                <!-- 留言列表区 -->
                <el-card class="message-card" v-if="activeItem && activeItem.id">
                    <template #header>
                        <span>{{activeItem.title}}</span>
                    </template>

                    <div class="message-list">
                        <div class="message-item">
                            <div class="flex items-center">
                                <el-avatar icon="User" :size="40"></el-avatar>
                                <span style="font-weight: 500; margin-left: 8px">
                                    {{ activeItem.sender.name || $t('messgae.userName') }}
                                </span>
                                <span class="time-text">
                                    {{ formatLoginTime(activeItem.created_at) }}
                                </span>
                            </div>

                            <div style="margin: 10px 0 5px 34px; line-height: 1.6">
                                {{ activeItem.content }}
                            </div>

                            <div style="margin-left: 34px">
                                <el-button color="#F16C2E" size="small" class="reply-btn" @click="toggleReply()">
                                    <el-icon size="mini" color="#ffffff">
                                        <TopLeft />
                                    </el-icon>
                                    {{ activeItem.showReplyForm ? $t('messgae.btn_txt_2') : $t('messgae.btn_txt_1') }}
                                </el-button>

                                <span v-if="activeItem.replies.length > 0" class="time-text"> {{ activeItem.replies.length }} 条回复 </span>
                            </div>

                            <!-- 回复输入框 -->
                            <div v-if="activeItem.showReplyForm" class="reply-form" style="margin-left: 34px; margin-top: 10px">
                                <el-form :model="activeItem.newReply" label-width="0">
                                    <el-form-item>
                                        <el-input v-model="activeItem.newReply.content" type="textarea" :rows="4" :placeholder="$t('messgae.placeholder_3')" resize="none" maxlength="500" show-word-limit></el-input>
                                    </el-form-item>

                                    <el-form-item>
                                        <el-button type="primary" color="#F16C2E" size="small" @click="addReply()" :loading="activeItem.replyLoading"> {{$t('messgae.btn_txt_1')}} </el-button>
                                        <el-button color="#C0C4CC" size="small" style="margin-left: 8px" @click="toggleReply()"> {{$t('messgae.btn_txt_3')}} </el-button>
                                    </el-form-item>
                                </el-form>
                            </div>

                            <!-- 回复列表 -->
                            <div v-if="activeItem.replies.length > 0" class="reply-list">
                                <div v-for="(reply, repIndex) in activeItem.replies" :key="reply.id" class="reply-item">
                                    <div class="flex items-center">
                                        <el-avatar icon="User" :size="40"></el-avatar>
                                        <span style="font-size: 13px; margin-left: 5px">
                                            {{ reply.sender.name || $t('messgae.userName') }}
                                        </span>
                                        <span class="time-text">
                                            {{ formatLoginTime(reply.created_at) }}
                                        </span>
                                    </div>
                                    <div class="reply-content">
                                        {{ reply.content }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-card>
                <p v-else class="no-data-list-tips">{{ $t('messgae.detail_tips_txt') }}</p>
            </div>
        </div>
        <AddMessageDialog ref="AddMessageDialogRef" :courseId="courseId" :receiverId="receiverId" @relRefresh="getDataList" />
    </div>
</template>

<script setup lang="ts">
import ForumManager from '@/components/ForumManager.vue'
import { computed, onMounted, ref, watch } from 'vue'
const targetExists = ref(false)
import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'
import { formatLoginTime } from '@/utils/global'
import type { noticesItem } from '@/types/user'
import CourseService from '@/api/course'
import type { Pagination } from '@/types/global'
import { ElCard, ElInput, ElButton, ElForm, ElFormItem, ElTag, ElAvatar, ElMessage } from 'element-plus'
import { Position } from '@element-plus/icons-vue'

import AddMessageDialog from './components/AddMessageDialog.vue'
// 分页器
const pagination = ref<Pagination>({
    page: 1,
    limit: 10,
    total: 0,
})
// 获取全部通知列表
const listLoading = ref(false)
const dataList = ref([])

const getDataList = () => {
    listLoading.value = true
    const searchData = {
        id: courseId.value,
        page: pagination.value.page,
        limit: pagination.value.limit,
    }
    CourseService.getMessageList(searchData)
        .then(res => {
            dataList.value = res.dataList || []
            pagination.value = res.pagination || pagination.value
        })
        .finally(() => {
            listLoading.value = false
        })
}
const AddMessageDialogRef = ref()
// 现实增加留言弹窗
const showAddMessageDialog = () => {
    AddMessageDialogRef.value.initDialog()
}

// 点击查看详情
const activeItem = ref()
const activeItemId = ref()
const clickDetailAction = (data: any) => {
    const objData = {
        ...data,
        showReplyForm: false,
        newReply: {
            content: '',
        },
        replyLoading: false,
    }
    activeItem.value = objData
    activeItemId.value = data.id
    readAction(activeItemId.value)
}
// 切换回复表单显示状态
const toggleReply = () => {
    activeItem.value.showReplyForm = !activeItem.value.showReplyForm
    // 重置回复内容
    if (activeItem.value.showReplyForm) {
        activeItem.value.newReply.content = ''
    }
}

// 添加回复
const addReply = () => {
    if (!activeItem.value.newReply.content.trim()) {
        ElMessage.warning('请输入回复内容')
        return
    }

    activeItem.value.replyLoading = true
    const params = {
        receiver_id: activeItem.value.sender_id,
        course_id: activeItem.value.course_id,
        parent_id: activeItem.value.id,
        content: activeItem.value.newReply.content
    }
    console.log('params', params)
    CourseService.postMessage(params).then(res => {
        activeItem.value.replies.push({
            id: res.data.items.id,
            content: res.data.items.content,
            sender: {
                name: activeItem.value.sender.name
            },
            created_at: res.data.items.created_at,
        })
        activeItem.value.showReplyForm = false
        activeItem.value.newReply.content = ''
        activeItem.value.replyLoading = false
    }).finally(() => {
        activeItem.value.replyLoading = false
    })
}


// 标记为已读
const readAction = (id: number) => {
    CourseService.postMessageRead(id).then(() => {})
}

import { useRoute } from 'vue-router'
const route = useRoute()
const courseId = ref()
const receiverId = ref()
// watch(
//   () => route.query.courseId,
//   (newId, oldId) => {
//     if(route.query.courseId){
//         console.log('courseId变化:', newId);
//         courseId.value = newId
//     }

//   },
//   { immediate: true } // 初始渲染时立即执行一次
// );
// watch(
//   () => route.query.receiverId,
//   (newId, oldId) => {
//     if(route.query.receiverId){
//         console.log('receiverId变化:', newId);
//         receiverId.value = newId
//     }

//   },
//   { immediate: true } // 初始渲染时立即执行一次
// );

onMounted(() => {
    courseId.value = route.query.courseId
    receiverId.value = route.query.receiverId
    targetExists.value = !!document.querySelector('#after-navigation')
    getDataList()
})
</script>

<style lang="less" scoped>
.title-wrap{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
}
.pagination-box {
    justify-content: center;
}
.notices-wrap {
    width: 100%;
    height: 600px;
    border-radius: 3px;
    border: 1px solid #e3e3e3;
    display: grid;
    grid-template-columns: 1fr 2fr;
    margin-top: 20px;
    .notices-left,
    .notices-right {
        height: 100%;
        overflow-y: auto;
    }
    .notices-left {
        border-right: 1px solid #e3e3e3;
        box-sizing: border-box;
        ul {
            padding: 10px 0;
            li {
                padding: 10px 10px 0;
                cursor: pointer;
                h3 {
                    font-size: 16px;
                    color: #000;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
                div {
                    display: flex;
                    justify-content: space-between;
                    align-content: center;
                    margin-top: 5px;
                    border-bottom: 1px solid #e3e3e3;
                    padding-bottom: 10px;
                    p {
                        font-size: 12px;
                        line-height: 2;
                    }
                }
            }
            .active {
                background-color: #f1f1f1;
            }
        }
    }
    .notices-right {
        box-sizing: border-box;
        padding: 15px;
        div {
            h3 {
                font-size: 16px;
                line-height: 1.4;
            }
            p {
                font-size: 12px;
                text-align: right;
                margin-top: 20px;
            }
        }
    }
}
.no-data-list-tips {
    text-align: center;
    padding-top: 50px;
    color: #4c4c4c;
    font-size: 14px;
}
.message-card {
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}
.reply-list {
    margin-top: 15px;
    padding-left: 40px;
    border-left: 2px solid #e4e7ed;
}
.reply-item {
    padding: 10px 0;
    border-bottom: 1px dashed #e4e7ed;
}
.reply-item:last-child {
    border-bottom: none;
}
.reply-form {
    margin-top: 10px;
    animation: fadeIn 0.3s ease;
}
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
.time-text {
    color: #909399;
    font-size: 12px;
    margin-left: 10px;
}
.reply-btn {
    font-size: 12px;
    padding: 3px 10px;
}
.message-item {
    padding: 15px 0;
    border-bottom: 1px solid #f0f2f5;
}
.message-item:last-child {
    border-bottom: none;
}
.flex{
    display: flex;
}
.items-center{
    align-items: center;
}
.reply-content{
    margin: 10px 0 0 28px; 
    font-size: 14px; 
    line-height: 1.5
}
</style>
